package com.om.abom.utils.test;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

import static com.om.abom.config.AbomConfig.*;
import static com.om.abom.utils.JschExecutor.processStream;

@Slf4j
public class ShellExecutorRemote
{
    private Connection connection;
    private final String ip;

    public ShellExecutorRemote(String ip)
    {
        this.ip = ip;
    }

    private boolean login()
    {
        boolean flg = false;
        try {
            connection = new Connection(ip);
            connection.connect();
            flg = connection.authenticateWithPassword(OS_USERNAME, OS_PASSWORD);
        } catch (IOException e) {
            log.error("exception message: ", e);
        }
        return flg;
    }

    public String execCmd(String command) throws Exception
    {
        InputStream stdOut = null;
        InputStream stdErr = null;
        String outStr = "";
        String outErr = "";
        String result;
        try {
            if (login()) {
                Session session = connection.openSession();
                session.execCommand(command);
                stdOut = session.getStdout();
                outStr = processStreamGobbler(stdOut);
                result = outStr;

                stdErr = session.getStderr();
                outErr = processStreamGobbler(stdErr);

                session.waitForCondition(ChannelCondition.EXIT_STATUS, SSH_SESSION_TIME_OUT);

                if(StringUtils.isBlank(result)){
                    //如果为得到标准输出为空，说明执行命令出错了
                    result = outErr;
                }
                // session.getExitStatus();
            } else {
                throw new Exception("登录远程机器失败" + ip);
            }
        } finally {
            if (connection != null) {
                connection.close();
            }
            IOUtils.closeQuietly(stdOut);
            IOUtils.closeQuietly(stdErr);
        }
        return result;
    }

    public static String processStreamGobbler(InputStream in)
    {
        return processStream(new StreamGobbler(in));
    }
}